package com.mlnx.device.service.impl;


import com.mlnx.bptp.BpPacket;
import com.mlnx.common.utils.MyLog;
import com.mlnx.device.manager.XmBpManager;
import com.mlnx.device.pojo.dto.AutoDetectCmdDto;
import com.mlnx.device.session.SessionManagerFactory;
import com.mlnx.tp.base.utils.LogUtils;
import io.netty.channel.Channel;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

/**
 * Created by amanda.shan on 2019/3/29.
 * 心脉血压计控制service
 */
@Service
public class XmBpControllService {


    private MyLog logger = MyLog.getLog(LogUtils.class);

    public static XmBpControllService xmBpervice;


    @PostConstruct
    private void init() {
        xmBpervice = this;
    }


    public boolean sendAutoDetect(AutoDetectCmdDto autoDetectCmd) throws InterruptedException {

        // 1、判断设备是否在线

        Channel channel=SessionManagerFactory.getInstance().getMutilDeviceSessionManager().getChannel(autoDetectCmd.getDeviceId());
        // 2、 TODO channel 发送命令 待补充
        BpPacket bpPacket = new BpPacket();
        if (autoDetectCmd.getDetectTime() != null) {
            bpPacket.getBody().setDetectTime(autoDetectCmd.getDetectTime());
        } else if (autoDetectCmd.getIsBegin() != null) {
            bpPacket.getBody().setIsBegin(autoDetectCmd.getIsBegin());
        } else if (autoDetectCmd.getDetectState() != null) {
            bpPacket.getBody().setDetectState(autoDetectCmd.getDetectState());
        } else if (autoDetectCmd.getRectify() != null) {
            if (autoDetectCmd.getRectify() == 1) {
                bpPacket.getBody().setRectify("1");
            }
        } else if (autoDetectCmd.getSynData() != null) {
            bpPacket.getBody().setSynData("1");
        }
        boolean sign = false;
        for (int i = 0; i < 3; i++) {
            if (!sign) {
                logger.info("发出BPPacket{}");
                channel.writeAndFlush(bpPacket);
                // 3、等待响应
                try {
                    AutoDetectCmdDto autoDetectCmd1 = XmBpManager.wait(autoDetectCmd);
                    sign = autoDetectCmd1.getKey().equals(autoDetectCmd.getKey());
                } catch (Exception e) {
                    logger.error(e, "等待超时异常:" + sign);
                }
            } else {

                break;
            }

        }
        return sign;
//        }


    }

}
